/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.registration.reports;

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.registration.core.Attendee;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @date Jun 27, 2012
 *
 * @author Ggutierrez
 */
public class PreInscriptionToPdf {

    Map messages;
    Image logo;
    Image logoSection;
    Format longFormat = new SimpleDateFormat("dd MMM yyyy");
    Format formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
    Format simpleFormat = new SimpleDateFormat("dd/MM/yyyy");
    PdfWriter writer;
    Font fBoldItalic = new Font(Font.HELVETICA, 11, Font.BOLDITALIC);
    Font fNormal = new Font(Font.HELVETICA, 11, Font.NORMAL);
    Font fUnderline = new Font(Font.HELVETICA, 11, Font.UNDERLINE);
    Font fItalic = new Font(Font.HELVETICA, 11, Font.ITALIC);
    Font fBold = new Font(Font.HELVETICA, 11, Font.BOLD);

    public PreInscriptionToPdf() {
        Properties props = new Properties();
        try {
            logo = Image.getInstance(getClass().getResource("/conescapan_blank.png"));
            logoSection = Image.getInstance(getClass().getResource("/ieee_nicaragua.gif"));
            messages = props;
        } catch (BadElementException ex) {
            Logger.getLogger(PreInscriptionToPdf.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(PreInscriptionToPdf.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PreInscriptionToPdf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void write(Attendee attendee, OutputStream out) {
        float margin = 70;
        float leading = 0;
        Document document = new Document(PageSize.LEGAL, margin, margin, leading, leading);
        try {
            writer = PdfWriter.getInstance(document, out);

            document.open();

            //addLogos(document, 50f, 940f);            
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            addContent(document, "Recibo", "Copia cliente", 20f, attendee);
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            
            //addLogos(document, 50f, 710f);
            addContent(document, "Orden de alojamiento", "Copia hotel", 20f, attendee);
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            
            //addLogos(document, 50f, 470f);
            addContent(document, "Entrega de materiales", "Copia inventario", 20f, attendee);
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            document.add(blankLine());
            document.add(new Paragraph("", new Font(Font.HELVETICA, 12, Font.BOLD, Color.RED)));
            
            //addLogos(document, 50f, 230f);
            addContent(document, "Orden de pago", "Copia caja", 20f, attendee);

            
            /* // LETTER SIZE
             addLogos(document, 200f, 700f);
             document.add(blankLine());
             addContent(document, 70f, attendee);

             addLogos(document, 200f, 450f);
             addContent(document, 70f, attendee);

             addLogos(document, 200f, 210f);
             addContent(document, 70f, attendee);
             */
            document.close();

        } catch (DocumentException ex) {
            Logger.getLogger(PreInscriptionToPdf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addContent(Document document, String type, String copy, Float spaceBefore, Attendee attendee) throws DocumentException {
        float leading = 20f;

        String id = customFormat("00000", attendee.getId().doubleValue());
        Paragraph number = new Paragraph("#" + id, new Font(Font.HELVETICA, 12, Font.BOLD, Color.RED));
        number.setAlignment(Element.ALIGN_RIGHT);
        number.setSpacingBefore(spaceBefore);
        //document.add(number);

        Paragraph title = new Paragraph(type, new Font(Font.HELVETICA, 16, Font.BOLD));
        title.setAlignment(Element.ALIGN_CENTER);
        document.add(title);

        String fullName = attendee.getFullName();
        Chunk p1 = new Chunk("\nRecibimos de ", fNormal);
        Chunk name = new Chunk(fullName, fBoldItalic);
        Chunk p2 = new Chunk(" la cantidad de ", fNormal);
        Float cost = attendee.getCost() != null ? attendee.getCost() : attendee.getCategory().getCost();
        Float roomCost = attendee.getRoomPlan() != null ? attendee.getRoomPlan().getPrice() : 0f;
        Float totalCost = cost + roomCost;
        Chunk amount = new Chunk(totalCost.toString(), fBoldItalic);
        Chunk p3 = new Chunk(" dólares americanos en concepto de ", fNormal);
        String category = attendee.getCategory() != null ? attendee.getCategory().getDescription() : "No definida";
        String room = attendee.getRoomPlan() != null ? attendee.getRoomPlan().getName() : "";
        Chunk cHosting = new Chunk(" Alojamiento " + room + " e", fBoldItalic);
        Chunk cCategory = new Chunk(" Inscripción " + category, fBoldItalic);
        Chunk p4 = new Chunk(" en Trigesima Tercera Convencion de Estudiantes de Centroamérica y Panama ", fNormal);
        Chunk p5 = new Chunk(" (CONESCAPAN XXXIII)", fBoldItalic);
        Chunk p6 = new Chunk(".", fNormal);

        Chunk place = new Chunk("\n\nDado en Managua, Nicaragua, a los ", fNormal);
        TimeZone tz = TimeZone.getDefault();
        Calendar today = Calendar.getInstance(tz);
        Chunk date = new Chunk(today.get(Calendar.DATE) + " días del mes de " + getMonthName(today.get(Calendar.MONTH)) + " de " + today.get(Calendar.YEAR) + ".", fNormal);

        Phrase phrase = new Phrase();
        phrase.add(p1);
        phrase.add(name);
        phrase.add(p2);
        phrase.add(amount);
        phrase.add(p3);
        if (attendee.getRoomPlan() != null) {
            phrase.add(cHosting);
        }
        phrase.add(cCategory);
        //phrase.add(p4);
        phrase.add(p5);
        phrase.add(p6);
        phrase.add(place);
        phrase.add(date);

        Paragraph paragraph = new Paragraph(leading);
        paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
        paragraph.add(phrase);

        document.add(paragraph);

        Paragraph footer = new Paragraph(copy, new Font(Font.HELVETICA, 8, Font.NORMAL));
        footer.setAlignment(Element.ALIGN_LEFT);
        footer.setSpacingBefore(20f);
        document.add(footer);

        Paragraph warning = new Paragraph("No es valido sin sello ni firma", new Font(Font.HELVETICA, 8, Font.NORMAL));
        footer.setAlignment(Element.ALIGN_LEFT);
        document.add(warning);
    }

    public void addLogos(Document document, float positionX, float positionY) throws DocumentException {
        logo.setAlignment(Image.ALIGN_CENTER);
        logo.setAbsolutePosition(positionX, positionY);
        logo.scalePercent(45f);
        document.add(logo);
/*
        logoSection.setAlignment(Image.ALIGN_CENTER);
        logoSection.setAbsolutePosition(positionX + 400f, positionY);
        logoSection.scalePercent(0f);
        document.add(logoSection);
*/
        document.add(Chunk.NEWLINE);
    }

    public void addHeader(Document document) throws DocumentException {
        Phrase p = new Phrase();
        String labelHeader1 = "CONESCAPAN XXXIII";
        String labelHeader2 = "MANAGUA, NICARAGUA";
        String labelHeader3 = "LEMA";

        Chunk header1 = new Chunk(labelHeader1 + "\n", new Font(Font.HELVETICA, 10, Font.NORMAL));
        Chunk header2 = new Chunk(labelHeader2 + "\n", new Font(Font.HELVETICA, 10, Font.NORMAL));
        Chunk header3 = new Chunk(labelHeader3 + "\n", new Font(Font.HELVETICA, 10, Font.NORMAL));
        p.add(header1);
        p.add(header2);
        p.add(header3);

        HeaderFooter header = new HeaderFooter(p, false);
        header.setAlignment(Element.ALIGN_CENTER);
        header.setBorder(0);
        document.setHeader(header);
    }

    public void addTitle(Document document) throws DocumentException {
        float[] widths = {0.6f};
        PdfPTable title = new PdfPTable(widths);
        title.setWidthPercentage(80);
        title.getDefaultCell().setBorder(0);

        Paragraph p = new Paragraph("Orden de pago", new Font(Font.HELVETICA, 16, Font.BOLD));
        p.setAlignment(Element.ALIGN_CENTER);
        document.add(p);
        document.add(blankLine());
    }

    public Paragraph blankLine() {
        //White Line
        String text = " ";
        Paragraph s = new Paragraph(text);
        s.setAlignment(Element.ALIGN_CENTER);
        return s;
    }

    public String getMonthName(int month) {
        Map<Integer, String> months = new HashMap<Integer, String>();
        months.put(0, "enero");
        months.put(1, "febrero");
        months.put(2, "marzo");
        months.put(3, "abril");
        months.put(4, "mayo");
        months.put(5, "junio");
        months.put(6, "julio");
        months.put(7, "agosto");
        months.put(8, "septiembre");
        months.put(9, "octubre");
        months.put(10, "noviembre");
        months.put(11, "diciembre");

        if (month >= 0 && month <= 11) {
            return months.get(month);
        } else {
            return "Mes no definido";
        }
    }

    public String customFormat(String pattern, double value) {
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        return output;
    }
}
